package com.heartbridge.downloader;

import com.github.heartbridge.fs.annotation.Handler;
import com.github.heartbridge.fs.annotation.RequestMapping;
import com.github.heartbridge.fs.annotation.RequestMethod;
import com.github.heartbridge.fs.annotation.RequestParam;
import com.github.heartbridge.fs.server.ServerStartParamsAware;
import com.github.heartbridge.fs.utils.FileUtils;

import com.heartbridge.fs.utils.WebResponse;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author GavinCook
 * @since 1.0.0
 **/
@Handler
public class DownloadHandler implements ServerStartParamsAware{

    private Logger logger = Logger.getLogger(getClass().getName());

    private String baseDir;

    @RequestMapping(value = "/remote/fetch", method = RequestMethod.GET)
    public WebResponse downloadRemoteFile(@RequestParam("url")String urlStr, @RequestParam(value = "suffix",defaultValue = "unknow")String suffix) throws IOException {
        if(urlStr == null){
            logger.log(Level.WARNING, "The url parameter must be provided");
            return WebResponse.fail("url parameter must be provided");
        }
        urlStr = URLDecoder.decode(urlStr, "utf-8");
        URL url = new URL(urlStr);
        if("unknow".equals(suffix)){
            int lastDotPostion = urlStr.lastIndexOf(".");
            if(lastDotPostion != -1){
                suffix = urlStr.substring(lastDotPostion+1);
            }
        }
        File file = new File(FileUtils.getTimestampPath(baseDir), System.currentTimeMillis() +"."+ suffix);
        file = FileUtils.getFileNotExists(file);
        FileUtils.createIfNotExists(file.getAbsolutePath(), false);
        FileUtils.save(url.openStream(), file);
        logger.log(Level.WARNING, "file from :{1} downloaded to {2} successfully.", new Object[]{url.toString(), file.getAbsolutePath()});
        return WebResponse.success(file.getAbsolutePath().substring(baseDir.length()-1).replaceAll("\\\\","/"));
    }

    @Override
    public void setStartParams(Map<String, String> map) {
        this.baseDir = map.get(ServerStartParamsAware.BASEDIR);
    }
}
